package com.example.scaffolding.composer.worker

import android.content.Context
import android.util.Log
import androidx.work.WorkerParameters
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.workDataOf
import com.example.scaffolding.composer.KEY_RESULT
import com.example.scaffolding.util.EventListener
import com.example.scaffolding.util.HttpDownloader
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.Exception
import java.util.concurrent.CountDownLatch

class ImageDownloadWorker(private val appContext: Context, workerParams: WorkerParameters)
    : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork() : Result {

        val url: String? = inputData.getString("IMAGE_URI")
        Log.d(TAG, "url = $url")
        if (url == null) {
            return Result.failure()
        }

        val Progress = "Progress"
        var result : Result = Result.success()
        val c : CountDownLatch = CountDownLatch(1)

        url?.let {
            downloadImage(appContext, it, object : EventListener<String> {
                override fun onProgress(progress: Int) {
                    GlobalScope.launch {
//                        setProgress(Data.Builder().putInt(Progress, progress).build())
                        setProgress(workDataOf(Progress to progress))
//                        Log.d(TAG, "progress = $progress")
                    }
                }

                override fun onError(e: Exception) {
                    result = Result.failure()
                    c.countDown()
                }

                override fun onSuccess(t: String) {

                    //...set the output, and we're done!

                    val output: Data = workDataOf(KEY_RESULT to t)
                    result = Result.success(output)
                    c.countDown()
                }

            });
        }
        c.await()
        return result
    }

    private fun downloadImage(context: Context, url: String, listener: EventListener<String>) {
        HttpDownloader.download(context, url, listener)
    }

    companion object {
        private const val TAG = "ImageDownloadWorker"
    }
}